<template>
  <view class="data-chart-container">
    <canvas 
      :canvas-id="chartId"
      :id="chartId"
      class="chart-canvas"
      :style="{ height: height + 'rpx' }"
    ></canvas>
  </view>
</template>

export default {
  props: {
    chartId: {
      type: String,
      required: true
    },
    type: {
      type: String,
      required: true,
      validator: (value) => ['line', 'bar', 'pie', 'doughnut'].includes(value)
    },
    data: {
      type: Object,
      required: true
    },
    options: {
      type: Object,
      default: () => ({})
    },
    height: {
      type: Number,
      default: 400
    },
    width: {
      type: Number,
      default: 750
    }
  },
  
  data() {
    return {
      chartInstance: null,
      defaultOptions: {
        line: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              display: true,
              position: 'top'
            }
          },
          scales: {
            y: {
              beginAtZero: true,
              grid: {
                color: '#e2e8f0'
              }
            },
            x: {
              grid: {
                display: false
              }
            }
          }
        },
        bar: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              display: true,
              position: 'top'
            }
          },
          scales: {
            y: {
              beginAtZero: true,
              grid: {
                color: '#e2e8f0'
              }
            },
            x: {
              grid: {
                display: false
              }
            }
          }
        },
        pie: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              display: true,
              position: 'bottom'
            }
          }
        },
        doughnut: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              display: true,
              position: 'bottom'
            }
          }
        }
      }
    }
  },
  
  methods: {
    // 渲染图表
    async renderChart() {
      await this.$nextTick()
      
      // 这里使用uni-app的canvas API
      // 实际项目中可以集成Chart.js或ECharts
      const ctx = uni.createCanvasContext(this.chartId, this)
      
      switch (this.type) {
        case 'line':
          this.renderLineChart(ctx)
          break
        case 'bar':
          this.renderBarChart(ctx)
          break
        case 'pie':
          this.renderPieChart(ctx)
          break
        case 'doughnut':
          this.renderDoughnutChart(ctx)
          break
      }
    }

// 渲染折线图
    renderLineChart(ctx) {
      const { labels, datasets } = this.data
      const canvasWidth = uni.upx2px(this.width)
      const canvasHeight = uni.upx2px(this.height)
      
      // 清空画布
      ctx.clearRect(0, 0, canvasWidth, canvasHeight)
      
      // 绘制网格线
      ctx.setStrokeStyle('#e2e8f0')
      ctx.setLineWidth(1)
      
      // 绘制坐标轴
      const padding = 60
      const chartWidth = canvasWidth - padding * 2
      const chartHeight = canvasHeight - padding * 2
      
      // 绘制Y轴
      ctx.beginPath()
      ctx.moveTo(padding, padding)
      ctx.lineTo(padding, canvasHeight - padding)
      ctx.stroke()
      
      // 绘制X轴
      ctx.beginPath()
      ctx.moveTo(padding, canvasHeight - padding)
      ctx.lineTo(canvasWidth - padding, canvasHeight - padding)
      ctx.stroke()
      
      // 绘制数据
      datasets.forEach((dataset, datasetIndex) => {
        ctx.setStrokeStyle(dataset.borderColor || '#3b82f6')
        ctx.setLineWidth(2)
        ctx.beginPath()
        
        const dataPoints = dataset.data
        const xStep = chartWidth / (labels.length - 1)
        const maxValue = Math.max(...dataPoints)
        const minValue = Math.min(...dataPoints)
        const valueRange = maxValue - minValue || 1
        
        dataPoints.forEach((value, index) => {
          const x = padding + index * xStep
          const y = canvasHeight - padding - ((value - minValue) / valueRange) * chartHeight
          
          if (index === 0) {
            ctx.moveTo(x, y)
          } else {
            ctx.lineTo(x, y)
          }
          
          // 绘制数据点
          ctx.beginPath()
          ctx.arc(x, y, 4, 0, 2 * Math.PI)
          ctx.setFillStyle(dataset.borderColor || '#3b82f6')
          ctx.fill()
        })
        
        ctx.stroke()
      })
      
      // 绘制标签
      ctx.setFontSize(12)
      ctx.setFillStyle('#64748b')
      labels.forEach((label, index) => {
        const x = padding + (chartWidth / (labels.length - 1)) * index
        ctx.fillText(label, x - 15, canvasHeight - padding + 20)
      })
      
      ctx.draw()
    },
    
    // 渲染柱状图
    renderBarChart(ctx) {
      const { labels, datasets } = this.data
      const canvasWidth = uni.upx2px(this.width)
      const canvasHeight = uni.upx2px(this.height)
      
      ctx.clearRect(0, 0, canvasWidth, canvasHeight)
      
      const padding = 60
      const chartWidth = canvasWidth - padding * 2
      const chartHeight = canvasHeight - padding * 2
      
      // 绘制坐标轴
      ctx.setStrokeStyle('#e2e8f0')
      ctx.setLineWidth(1)
      
      ctx.beginPath()
      ctx.moveTo(padding, padding)
      ctx.lineTo(padding, canvasHeight - padding)
      ctx.stroke()
      
      ctx.beginPath()
      ctx.moveTo(padding, canvasHeight - padding)
      ctx.lineTo(canvasWidth - padding, canvasHeight - padding)
      ctx.stroke()
      
      // 绘制柱状图
      const barWidth = chartWidth / labels.length / datasets.length * 0.8
      const maxValue = Math.max(...datasets.flatMap(d => d.data))
      
      datasets.forEach((dataset, datasetIndex) => {
        ctx.setFillStyle(dataset.backgroundColor || '#3b82f6')
        
        dataset.data.forEach((value, index) => {
          const x = padding + (chartWidth / labels.length) * index + barWidth * datasetIndex
          const barHeight = (value / maxValue) * chartHeight
          const y = canvasHeight - padding - barHeight
          
          ctx.fillRect(x, y, barWidth, barHeight)
        })
      })
      
      // 绘制标签
      ctx.setFontSize(12)
      ctx.setFillStyle('#64748b')
      labels.forEach((label, index) => {
        const x = padding + (chartWidth / labels.length) * index + chartWidth / labels.length / 2
        ctx.fillText(label, x - 15, canvasHeight - padding + 20)
      })
      
      ctx.draw()
    },
    
    // 渲染饼图
    renderPieChart(ctx) {
      const { labels, datasets } = this.data
      const canvasWidth = uni.upx2px(this.width)
      const canvasHeight = uni.upx2px(this.height)
      
      ctx.clearRect(0, 0, canvasWidth, canvasHeight)
      
      const centerX = canvasWidth / 2
      const centerY = canvasHeight / 2
      const radius = Math.min(canvasWidth, canvasHeight) / 3
      
      const dataset = datasets[0]
      const total = dataset.data.reduce((sum, value) => sum + value, 0)
      
      let currentAngle = -Math.PI / 2
      
      dataset.data.forEach((value, index) => {
        const sliceAngle = (value / total) * 2 * Math.PI
        const endAngle = currentAngle + sliceAngle
        
        ctx.beginPath()
        ctx.moveTo(centerX, centerY)
        ctx.arc(centerX, centerY, radius, currentAngle, endAngle)
        ctx.closePath()
        
        ctx.setFillStyle(dataset.backgroundColor?.[index] || '#3b82f6')
        ctx.fill()
        
        currentAngle = endAngle
      })
      
      ctx.draw()
    },
    
    // 渲染环形图
    renderDoughnutChart(ctx) {
      const { labels, datasets } = this.data
      const canvasWidth = uni.upx2px(this.width)
      const canvasHeight = uni.upx2px(this.height)
      
      ctx.clearRect(0, 0, canvasWidth, canvasHeight)
      
      const centerX = canvasWidth / 2
      const centerY = canvasHeight / 2
      const outerRadius = Math.min(canvasWidth, canvasHeight) / 3
      const innerRadius = outerRadius * 0.6
      
      const dataset = datasets[0]
      const total = dataset.data.reduce((sum, value) => sum + value, 0)
      
      let currentAngle = -Math.PI / 2
      
      dataset.data.forEach((value, index) => {
        const sliceAngle = (value / total) * 2 * Math.PI
        const endAngle = currentAngle + sliceAngle
        
        ctx.beginPath()
        ctx.arc(centerX, centerY, outerRadius, currentAngle, endAngle)
        ctx.arc(centerX, centerY, innerRadius, endAngle, currentAngle, true)
        ctx.closePath()
        
        ctx.setFillStyle(dataset.backgroundColor?.[index] || '#3b82f6')
        ctx.fill()
        
        currentAngle = endAngle
      })
      
      ctx.draw()
    }
  },
  
  watch: {
    // 监听数据变化
    data: {
      handler() {
        this.renderChart()
      },
      deep: true
    },
    
    // 监听类型变化
    type() {
      this.renderChart()
    }
  },
  
  onLoad() {
    this.renderChart()
  }
</script>

<style lang="scss" scoped>
.data-chart-container {
  width: 100%;
  
  .chart-canvas {
    width: 100%;
    height: 100%;
  }
}
</style>